<template>
  <div class="module-card">
    <div class="module-header">
      <h3>部门会议管理</h3>
      <div class="header-actions">
        <button 
          @click="openAddMeetingModal"
          class="btn-primary"
        >
          <i class="icon-plus"></i> 新增会议
        </button>
      </div>
    </div>
    
    <!-- 会议列表 -->
    <div class="meeting-list">
      <div class="list-header">
        <div class="search-filter">
          <input 
            type="text" 
            v-model="searchKeyword"
            placeholder="搜索会议标题或主持人..."
            class="search-input"
            @keyup.enter="searchMeetings"
          />
          <button 
            @click="searchMeetings"
            class="btn-search"
          >
            <i class="icon-search"></i>
          </button>
          <button 
            @click="resetSearch"
            class="btn-reset"
          >
            重置
          </button>
        </div>
        <div class="view-toggle">
          <button 
            :class="['btn-view', { active: viewMode === 'list' }]"
            @click="viewMode = 'list'"
          >
            <i class="icon-list"></i> 列表
          </button>
          <button 
            :class="['btn-view', { active: viewMode === 'calendar' }]"
            @click="viewMode = 'calendar'"
          >
            <i class="icon-calendar"></i> 日历
          </button>
        </div>
      </div>
      
      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="list-content">
        <table class="meeting-table">
          <thead>
            <tr>
              <th>序号</th>
              <th>会议标题</th>
              <th>会议日期</th>
              <th>会议时间</th>
              <th>主持人</th>
              <th>参会人数</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(meeting, index) in paginatedMeetings" :key="meeting.id">
              <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
              <td class="meeting-title" @click="viewMeetingDetail(meeting)">{{ meeting.title }}</td>
              <td>{{ formatDate(meeting.date) }}</td>
              <td>{{ formatTime(meeting.startTime) }} - {{ formatTime(meeting.endTime) }}</td>
              <td>{{ meeting.host || '未设置' }}</td>
              <td>{{ meeting.participantCount || 0 }}</td>
              <td>
                <span :class="['status-tag', meeting.status]">
                  {{ getStatusText(meeting.status) }}
                </span>
              </td>
              <td class="action-buttons">
                <button 
                  @click="editMeeting(meeting)"
                  class="btn-edit"
                  :disabled="meeting.status === 'completed'"
                  title="编辑会议"
                >
                  <i class="icon-edit"></i>
                </button>
                <button 
                  @click="deleteMeeting(meeting.id)"
                  class="btn-delete"
                  :disabled="meeting.status === 'completed'"
                  title="删除会议"
                >
                  <i class="icon-trash-o"></i>
                </button>
              </td>
            </tr>
          </tbody>
        </table>
        
        <!-- 空状态 -->
        <div v-if="filteredMeetings.length === 0" class="empty-state">
          <i class="icon-meeting"></i>
          <p>暂无会议记录</p>
          <button 
            @click="openAddMeetingModal"
            class="btn-primary"
          >
            <i class="icon-plus"></i> 创建第一个会议
          </button>
        </div>
        
        <!-- 分页 -->
        <div v-if="filteredMeetings.length > 0" class="pagination">
          <button 
            @click="prevPage"
            :disabled="currentPage === 1"
            class="btn-page"
          >
            <i class="icon-chevron-left"></i>
          </button>
          <div class="page-numbers">
            <button 
              v-for="page in visiblePages"
              :key="page"
              @click="goToPage(page)"
              :class="['btn-page-number', { active: page === currentPage }]"
            >
              {{ page }}
            </button>
          </div>
          <button 
            @click="nextPage"
            :disabled="currentPage === totalPages"
            class="btn-page"
          >
            <i class="icon-chevron-right"></i>
          </button>
          <div class="page-info">
            共 {{ filteredMeetings.length }} 条记录，第 {{ currentPage }}/{{ totalPages }} 页
          </div>
        </div>
      </div>
      
      <!-- 日历视图 -->
      <div v-else class="calendar-content">
        <div class="calendar-header">
          <button @click="prevMonth" class="btn-nav">
            <i class="icon-chevron-left"></i>
          </button>
          <h4>{{ currentMonthYear }}</h4>
          <button @click="nextMonth" class="btn-nav">
            <i class="icon-chevron-right"></i>
          </button>
        </div>
        
        <div class="calendar-weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
        </div>
        
        <div class="calendar-days">
          <div 
            v-for="day in calendarDays"
            :key="day.date.toDateString()"
            :class="['calendar-day', { 'other-month': !day.isCurrentMonth, 'today': day.isToday }]"
          >
            <span class="day-number">{{ day.day }}</span>
            <div class="day-meetings">
              <div 
                v-for="meeting in day.meetings"
                :key="meeting.id"
                :class="['meeting-item', meeting.status]"
                @click="viewMeetingDetail(meeting)"
              >
                <i :class="['icon', getMeetingIcon(meeting.status)]"></i>
                <span class="meeting-item-title">{{ truncateText(meeting.title, 10) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 会议详情弹窗 -->
    <div class="modal-overlay" v-if="showMeetingDetail" @click="closeMeetingDetail">
      <div class="modal-content meeting-detail-modal" @click.stop>
        <div class="modal-header">
          <h3>会议详情</h3>
          <button @click="closeMeetingDetail" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedMeeting" class="meeting-detail-content">
            <div class="detail-row">
              <label>会议标题</label>
              <div>{{ selectedMeeting.title }}</div>
            </div>
            <div class="detail-row">
              <label>会议日期</label>
              <div>{{ formatDate(selectedMeeting.date) }}</div>
            </div>
            <div class="detail-row">
              <label>会议时间</label>
              <div>{{ formatTime(selectedMeeting.startTime) }} - {{ formatTime(selectedMeeting.endTime) }}</div>
            </div>
            <div class="detail-row">
              <label>主持人</label>
              <div>{{ selectedMeeting.host || '未设置' }}</div>
            </div>
            <div class="detail-row">
              <label>会议地点</label>
              <div>{{ selectedMeeting.location || '未设置' }}</div>
            </div>
            <div class="detail-row">
              <label>会议状态</label>
              <span :class="['status-tag', selectedMeeting.status]">
                {{ getStatusText(selectedMeeting.status) }}
              </span>
            </div>
            <div class="detail-row">
              <label>会议内容</label>
              <div class="meeting-content" v-html="formatContent(selectedMeeting.content)"></div>
            </div>
            <div class="detail-row">
              <label>参会人员</label>
              <div class="participants">
                <div 
                  v-for="participant in selectedMeeting.participants || []"
                  :key="participant.id"
                  class="participant-tag"
                >
                  {{ participant.name }}
                </div>
                <div v-if="(selectedMeeting.participants || []).length === 0">
                  暂无参会人员
                </div>
              </div>
            </div>
            <div class="detail-row">
              <label>创建时间</label>
              <div>{{ formatDateTime(selectedMeeting.createdAt) }}</div>
            </div>
            <div class="detail-row">
              <label>更新时间</label>
              <div>{{ formatDateTime(selectedMeeting.updatedAt) }}</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button 
            @click="editMeeting(selectedMeeting)"
            v-if="selectedMeeting.status !== 'completed'"
            class="btn-primary"
          >
            <i class="icon-edit"></i> 编辑
          </button>
          <button @click="closeMeetingDetail" class="btn-secondary">
            关闭
          </button>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑会议弹窗 -->
    <div class="modal-overlay" v-if="showMeetingModal" @click="closeMeetingModal">
      <div class="modal-content meeting-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditingMeeting ? '编辑会议' : '新增会议' }}</h3>
          <button @click="closeMeetingModal" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveMeeting">
            <div class="form-group">
              <label>会议标题 <span class="required">*</span></label>
              <input 
                type="text" 
                v-model="formData.title"
                placeholder="请输入会议标题"
                required
                class="form-input"
                :class="{ 'error': errors.title }"
              />
              <div v-if="errors.title" class="error-message">{{ errors.title }}</div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label>会议日期 <span class="required">*</span></label>
                <input 
                  type="date" 
                  v-model="formData.date"
                  required
                  class="form-input"
                  :class="{ 'error': errors.date }"
                  :min="new Date().toISOString().split('T')[0]"
                />
                <div v-if="errors.date" class="error-message">{{ errors.date }}</div>
              </div>
              
              <div class="form-group">
                <label>开始时间 <span class="required">*</span></label>
                <input 
                  type="time" 
                  v-model="formData.startTime"
                  required
                  class="form-input"
                  :class="{ 'error': errors.startTime }"
                />
                <div v-if="errors.startTime" class="error-message">{{ errors.startTime }}</div>
              </div>
              
              <div class="form-group">
                <label>结束时间 <span class="required">*</span></label>
                <input 
                  type="time" 
                  v-model="formData.endTime"
                  required
                  class="form-input"
                  :class="{ 'error': errors.endTime }"
                />
                <div v-if="errors.endTime" class="error-message">{{ errors.endTime }}</div>
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label>主持人</label>
                <input 
                  type="text" 
                  v-model="formData.host"
                  placeholder="请输入主持人姓名"
                  class="form-input"
                />
              </div>
              
              <div class="form-group">
                <label>会议地点</label>
                <input 
                  type="text" 
                  v-model="formData.location"
                  placeholder="请输入会议地点"
                  class="form-input"
                />
              </div>
            </div>
            
            <div class="form-group">
              <label>会议内容</label>
              <textarea 
                v-model="formData.content"
                placeholder="请输入会议内容..."
                rows="6"
                class="form-textarea"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label>参会人员</label>
              <div class="participants-selector">
                <div class="search-participants">
                  <input 
                    type="text" 
                    v-model="participantSearch"
                    placeholder="搜索成员..."
                    class="form-input"
                  />
                  <button 
                    @click="searchDepartmentMembers"
                    class="btn-search"
                  >
                    <i class="icon-search"></i>
                  </button>
                </div>
                
                <div class="available-participants" v-if="showParticipantList">
                  <div 
                    v-for="member in filteredParticipants"
                    :key="member.id"
                    :class="['participant-option', { 'selected': isParticipantSelected(member.id) }]"
                    @click="toggleParticipant(member)"
                  >
                    <span class="participant-name">{{ member.name }}</span>
                    <span class="participant-info">{{ member.studentId }} - {{ member.major }}</span>
                  </div>
                </div>
                
                <div class="selected-participants">
                  <div 
                    v-for="participant in formData.participants"
                    :key="participant.id"
                    class="selected-participant"
                  >
                    <span>{{ participant.name }}</span>
                    <button 
                      @click="removeParticipant(participant.id)"
                      class="btn-remove-participant"
                    >
                      <i class="icon-times"></i>
                    </button>
                  </div>
                  <div v-if="formData.participants.length === 0" class="empty-participants">
                    暂无选中的参会人员
                  </div>
                </div>
              </div>
            </div>
            
            <div class="form-actions">
              <button 
                type="submit"
                :disabled="saving"
                class="btn-primary"
              >
                {{ saving ? '保存中...' : '保存' }}
              </button>
              <button 
                type="button"
                @click="closeMeetingModal"
                class="btn-secondary"
              >
                取消
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'

// 状态管理
const meetings = ref([])
const filteredMeetings = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const viewMode = ref('list')
const showMeetingModal = ref(false)
const showMeetingDetail = ref(false)
const selectedMeeting = ref(null)
const isEditingMeeting = ref(false)
const saving = ref(false)
const errors = ref({})
const departmentMembers = ref([])
const showParticipantList = ref(false)
const participantSearch = ref('')

// 日历视图状态
const currentDate = ref(new Date())
const weekdays = ref(['日', '一', '二', '三', '四', '五', '六'])
const calendarDays = ref([])

// 表单数据
const formData = ref({
  id: '',
  title: '',
  date: '',
  startTime: '',
  endTime: '',
  host: '',
  location: '',
  content: '',
  participants: [],
  departmentId: 5,
  status: 'scheduled'
})

// 计算属性：分页数据
const paginatedMeetings = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredMeetings.value.slice(startIndex, endIndex)
})

// 计算属性：总页数
const totalPages = computed(() => {
  return Math.ceil(filteredMeetings.value.length / pageSize.value)
})

// 计算属性：可见页码
const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value
  
  // 显示当前页及前后各2页
  for (let i = Math.max(1, current - 2); i <= Math.min(total, current + 2); i++) {
    pages.push(i)
  }
  
  return pages
})

// 计算属性：当前月份和年份
const currentMonthYear = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth() + 1
  return `${year}年${month}月`
})

// 获取部门会议列表
const fetchMeetings = async () => {
  try {
    const response = await fetch('http://localhost:8080/meeting/department/5')
    const result = await response.json()
    
    if (result.code === 200) {
      meetings.value = result.data
      filteredMeetings.value = result.data
      initializeCalendar()
    } else {
      console.error('获取会议列表失败:', result.message)
      showToast('获取会议列表失败', 'error')
    }
  } catch (error) {
    console.error('获取会议列表失败:', error)
    showToast('无法连接到服务器，请稍后重试', 'error')
  }
}

// 搜索会议
const searchMeetings = () => {
  if (!searchKeyword.value.trim()) {
    filteredMeetings.value = meetings.value
  } else {
    const keyword = searchKeyword.value.toLowerCase().trim()
    filteredMeetings.value = meetings.value.filter(meeting => 
      meeting.title.toLowerCase().includes(keyword) ||
      (meeting.host && meeting.host.toLowerCase().includes(keyword))
    )
  }
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  filteredMeetings.value = meetings.value
  currentPage.value = 1
}

// 分页功能
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const goToPage = (page) => {
  currentPage.value = page
}

// 打开新增会议弹窗
const openAddMeetingModal = () => {
  isEditingMeeting.value = false
  formData.value = {
    id: '',
    title: '',
    date: '',
    startTime: '',
    endTime: '',
    host: '',
    location: '',
    content: '',
    participants: [],
    departmentId: 5,
    status: 'scheduled'
  }
  errors.value = {}
  showMeetingModal.value = true
}

// 编辑会议
const editMeeting = (meeting) => {
  isEditingMeeting.value = true
  formData.value = {
    id: meeting.id,
    title: meeting.title,
    date: meeting.date,
    startTime: meeting.startTime,
    endTime: meeting.endTime,
    host: meeting.host || '',
    location: meeting.location || '',
    content: meeting.content || '',
    participants: meeting.participants || [],
    departmentId: 5,
    status: meeting.status
  }
  errors.value = {}
  showMeetingModal.value = true
  closeMeetingDetail()
}

// 查看会议详情
const viewMeetingDetail = (meeting) => {
  selectedMeeting.value = meeting
  showMeetingDetail.value = true
}

// 关闭会议详情弹窗
const closeMeetingDetail = () => {
  showMeetingDetail.value = false
  selectedMeeting.value = null
}

// 关闭会议编辑弹窗
const closeMeetingModal = () => {
  showMeetingModal.value = false
  formData.value = {
    id: '',
    title: '',
    date: '',
    startTime: '',
    endTime: '',
    host: '',
    location: '',
    content: '',
    participants: [],
    departmentId: 5,
    status: 'scheduled'
  }
  errors.value = {}
  showParticipantList.value = false
  participantSearch.value = ''
}

// 验证表单
const validateForm = () => {
  const newErrors = {}
  
  if (!formData.value.title.trim()) {
    newErrors.title = '请输入会议标题'
  }
  
  if (!formData.value.date) {
    newErrors.date = '请选择会议日期'
  }
  
  if (!formData.value.startTime) {
    newErrors.startTime = '请选择开始时间'
  }
  
  if (!formData.value.endTime) {
    newErrors.endTime = '请选择结束时间'
  }
  
  // 验证时间逻辑
  if (formData.value.date && formData.value.startTime && formData.value.endTime) {
    const startDateTime = new Date(`${formData.value.date}T${formData.value.startTime}`)
    const endDateTime = new Date(`${formData.value.date}T${formData.value.endTime}`)
    const now = new Date()
    
    if (startDateTime >= endDateTime) {
      newErrors.endTime = '结束时间必须晚于开始时间'
    }
    
    if (startDateTime < now && !isEditingMeeting.value) {
      newErrors.startTime = '开始时间不能早于当前时间'
    }
  }
  
  errors.value = newErrors
  return Object.keys(newErrors).length === 0
}

// 保存会议
const saveMeeting = async () => {
  if (!validateForm()) {
    return
  }
  
  saving.value = true
  try {
    // 准备表单数据
    const meetingData = {
      ...formData.value,
      departmentId: 5
    }
    
    const url = isEditingMeeting.value 
      ? `http://localhost:8080/meeting/update/${formData.value.id}`
      : 'http://localhost:8080/meeting/create'
    
    const method = isEditingMeeting.value ? 'PUT' : 'POST'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(meetingData)
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      // 重新获取会议列表
      await fetchMeetings()
      closeMeetingModal()
      showToast(isEditingMeeting.value ? '会议更新成功' : '会议创建成功', 'success')
    } else {
      console.error('保存会议失败:', result.message)
      showToast('保存会议失败：' + result.message, 'error')
    }
  } catch (error) {
    console.error('保存会议失败:', error)
    showToast('无法连接到服务器，请稍后重试', 'error')
  } finally {
    saving.value = false
  }
}

// 删除会议
const deleteMeeting = async (id) => {
  if (!confirm('确定要删除这个会议吗？此操作不可撤销。')) {
    return
  }
  
  try {
    const response = await fetch(`http://localhost:8080/meeting/delete/${id}`, {
      method: 'DELETE'
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      // 重新获取会议列表
      await fetchMeetings()
      showToast('会议删除成功', 'success')
    } else {
      console.error('删除会议失败:', result.message)
      showToast('删除会议失败：' + result.message, 'error')
    }
  } catch (error) {
    console.error('删除会议失败:', error)
    showToast('无法连接到服务器，请稍后重试', 'error')
  }
}

// 获取部门成员
const searchDepartmentMembers = async () => {
  try {
    const response = await fetch(`http://localhost:8080/user/department/5?search=${participantSearch.value}`)
    const result = await response.json()
    
    if (result.code === 200) {
      departmentMembers.value = result.data
      showParticipantList.value = true
    } else {
      console.error('获取部门成员失败:', result.message)
      showToast('获取部门成员失败', 'error')
    }
  } catch (error) {
    console.error('获取部门成员失败:', error)
    showToast('无法连接到服务器，请稍后重试', 'error')
  }
}

// 检查成员是否已被选中
const isParticipantSelected = (id) => {
  return formData.value.participants.some(p => p.id === id)
}

// 切换成员选中状态
const toggleParticipant = (member) => {
  const index = formData.value.participants.findIndex(p => p.id === member.id)
  
  if (index > -1) {
    formData.value.participants.splice(index, 1)
  } else {
    formData.value.participants.push(member)
  }
}

// 移除参会成员
const removeParticipant = (id) => {
  const index = formData.value.participants.findIndex(p => p.id === id)
  if (index > -1) {
    formData.value.participants.splice(index, 1)
  }
}

// 过滤后的成员列表
const filteredParticipants = computed(() => {
  if (!participantSearch.value.trim()) {
    return departmentMembers.value
  }
  
  const keyword = participantSearch.value.toLowerCase().trim()
  return departmentMembers.value.filter(member => 
    member.name.toLowerCase().includes(keyword) ||
    member.studentId.toLowerCase().includes(keyword)
  )
})

// 初始化日历
const initializeCalendar = () => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  
  // 当月第一天
  const firstDay = new Date(year, month, 1)
  // 当月最后一天
  const lastDay = new Date(year, month + 1, 0)
  
  // 当月第一天是星期几 (0-6)
  const firstDayOfWeek = firstDay.getDay()
  // 当月的天数
  const daysInMonth = lastDay.getDate()
  
  // 上个月的最后几天
  const prevMonthLastDay = new Date(year, month, 0).getDate()
  
  const days = []
  
  // 添加上个月的尾巴
  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const date = new Date(year, month, -i)
    days.push({
      day: prevMonthLastDay - i,
      date: date,
      isCurrentMonth: false,
      isToday: isSameDay(date, new Date()),
      meetings: []
    })
  }
  
  // 添加当月的天数
  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(year, month, i)
    const dayMeetings = meetings.value.filter(meeting => {
      const meetingDate = new Date(meeting.date)
      return isSameDay(meetingDate, date)
    })
    
    days.push({
      day: i,
      date: date,
      isCurrentMonth: true,
      isToday: isSameDay(date, new Date()),
      meetings: dayMeetings
    })
  }
  
  // 添加下个月的开头，凑够35天（5周）
  const remainingDays = 35 - days.length
  for (let i = 1; i <= remainingDays; i++) {
    const date = new Date(year, month + 1, i)
    days.push({
      day: i,
      date: date,
      isCurrentMonth: false,
      isToday: isSameDay(date, new Date()),
      meetings: []
    })
  }
  
  calendarDays.value = days
}

// 切换到上个月
const prevMonth = () => {
  currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() - 1, 1)
  initializeCalendar()
}

// 切换到下个月
const nextMonth = () => {
  currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() + 1, 1)
  initializeCalendar()
}

// 辅助函数：检查两个日期是否是同一天
const isSameDay = (date1, date2) => {
  return (
    date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
  )
}

// 辅助函数：格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
}

// 辅助函数：格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  return timeString
}

// 辅助函数：格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
}

// 辅助函数：补零
const padZero = (num) => {
  return num.toString().padStart(2, '0')
}

// 辅助函数：获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    scheduled: '已安排',
    ongoing: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 辅助函数：获取会议图标
const getMeetingIcon = (status) => {
  const iconMap = {
    scheduled: 'icon-clock-o',
    ongoing: 'icon-play-circle-o',
    completed: 'icon-check-circle-o',
    cancelled: 'icon-times-circle-o'
  }
  return iconMap[status] || 'icon-meeting'
}

// 辅助函数：截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.slice(0, maxLength) + '...'
}

// 辅助函数：格式化会议内容
const formatContent = (content) => {
  if (!content) return ''
  // 将换行符转换为<br>
  return content.replace(/\n/g, '<br>')
}

// 显示提示信息
const showToast = (message, type = 'info') => {
  // 这里可以根据实际项目中的toast组件来实现
  alert(message)
}

// 监听搜索关键词变化
watch(searchKeyword, (newValue) => {
  if (!newValue.trim()) {
    filteredMeetings.value = meetings.value
    currentPage.value = 1
  }
})

// 监听会议数据变化，重新初始化日历
watch(meetings, () => {
  if (viewMode.value === 'calendar') {
    initializeCalendar()
  }
}, { deep: true })

// 监听视图模式变化
watch(viewMode, (newMode) => {
  if (newMode === 'calendar') {
    initializeCalendar()
  }
})

// 监听当前日期变化
watch(currentDate, () => {
  initializeCalendar()
}, { deep: true })

// 组件挂载时获取会议列表
onMounted(() => {
  fetchMeetings()
})
</script>

<style>
/* 全局模块容器样式 */
.module-card {
  width: 100%;
  max-width: 1400px;
  margin: 24px auto;
  padding: 32px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  font-family: "Inter", system-ui, -apple-system, sans-serif;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.module-header h3 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 按钮样式 */
.btn-primary {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-primary:hover:not(:disabled) {
  background: #66b1ff;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background: #f0f0f0;
  color: #666;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-secondary:hover {
  background: #e0e0e0;
}

/* 会议列表样式 */
.meeting-list {
  width: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-filter {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  max-width: 500px;
}

.search-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.btn-search {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-search:hover {
  background: #66b1ff;
}

.btn-reset {
  background: #f0f0f0;
  color: #666;
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.btn-reset:hover {
  background: #e0e0e0;
}

.view-toggle {
  display: flex;
  gap: 8px;
  background: #f5f7fa;
  padding: 4px;
  border-radius: 8px;
}

.btn-view {
  background: transparent;
  color: #666;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
}

.btn-view.active {
  background: white;
  color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.btn-view:hover:not(.active) {
  color: #409eff;
}

/* 表格样式 */
.meeting-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.meeting-table th {
  background: #f8f9fa;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #f0f0f0;
}

.meeting-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.meeting-table tr:last-child td {
  border-bottom: none;
}

.meeting-table tr:hover {
  background: #f8f9fa;
}

.meeting-title {
  cursor: pointer;
  color: #409eff;
  font-weight: 500;
  transition: color 0.3s ease;
}

.meeting-title:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 状态标签 */
.status-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.scheduled {
  background: #e6f7ff;
  color: #1890ff;
}

.status-tag.ongoing {
  background: #fff7e6;
  color: #fa8c16;
}

.status-tag.completed {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.cancelled {
  background: #fff2f0;
  color: #f5222d;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-edit,
.btn-delete {
  background: transparent;
  border: none;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
}

.btn-edit:hover:not(:disabled) {
  background: #ecf5ff;
  color: #409eff;
}

.btn-delete:hover:not(:disabled) {
  background: #fff2f0;
  color: #f5222d;
}

.btn-edit:disabled,
.btn-delete:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 16px;
  display: block;
}

.empty-state p {
  font-size: 16px;
  margin-bottom: 24px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
}

.btn-page {
  background: #f5f7fa;
  color: #666;
  border: none;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-page:hover:not(:disabled) {
  background: #ecf5ff;
  color: #409eff;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.btn-page-number {
  background: #f5f7fa;
  color: #666;
  border: none;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 36px;
  text-align: center;
}

.btn-page-number:hover:not(.active) {
  background: #ecf5ff;
  color: #409eff;
}

.btn-page-number.active {
  background: #409eff;
  color: white;
}

.page-info {
  margin-left: 16px;
  font-size: 14px;
  color: #666;
}

/* 日历视图样式 */
.calendar-content {
  width: 100%;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.calendar-header h4 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.btn-nav {
  background: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-nav:hover {
  background: #66b1ff;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  margin-bottom: 8px;
}

.weekday {
  text-align: center;
  font-weight: 600;
  color: #666;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 6px;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.calendar-day {
  min-height: 100px;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  position: relative;
  transition: all 0.3s ease;
}

.calendar-day:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.calendar-day.other-month {
  background: #f8f9fa;
  opacity: 0.6;
}

.calendar-day.today {
  background: #ecf5ff;
  border-color: #409eff;
}

.day-number {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  display: inline-block;
}

.day-meetings {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-height: 80px;
  overflow-y: auto;
}

.meeting-item {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.meeting-item.scheduled {
  background: #e6f7ff;
  color: #1890ff;
}

.meeting-item.ongoing {
  background: #fff7e6;
  color: #fa8c16;
}

.meeting-item.completed {
  background: #f6ffed;
  color: #52c41a;
}

.meeting-item.cancelled {
  background: #fff2f0;
  color: #f5222d;
}

.meeting-item:hover {
  opacity: 0.8;
  transform: translateX(2px);
}

.meeting-item-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

.meeting-detail-modal {
  max-width: 800px;
}

.meeting-modal {
  max-width: 900px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.btn-close {
  background: transparent;
  border: none;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s ease;
  padding: 4px;
}

.btn-close:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 会议详情样式 */
.meeting-detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.detail-row label {
  width: 120px;
  font-weight: 600;
  color: #666;
  flex-shrink: 0;
}

.detail-row > div {
  flex: 1;
  color: #333;
  line-height: 1.6;
}

.meeting-content {
  white-space: pre-wrap;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  line-height: 1.8;
}

.participants {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.participant-tag {
  background: #f0f0f0;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  color: #666;
}

/* 表单样式 */
.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #f5222d;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  font-family: inherit;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-input.error,
.form-textarea.error {
  border-color: #f5222d;
}

.error-message {
  color: #f5222d;
  font-size: 12px;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 参会人员选择器样式 */
.participants-selector {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
}

.search-participants {
  display: flex;
  padding: 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.search-participants .form-input {
  flex: 1;
  border-radius: 4px 0 0 4px;
  border-right: none;
}

.search-participants .btn-search {
  border-radius: 0 4px 4px 0;
  padding: 10px 16px;
}

.available-participants {
  max-height: 200px;
  overflow-y: auto;
  border-bottom: 1px solid #e0e0e0;
}

.participant-option {
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
}

.participant-option:last-child {
  border-bottom: none;
}

.participant-option:hover {
  background: #f8f9fa;
}

.participant-option.selected {
  background: #ecf5ff;
  color: #409eff;
}

.participant-name {
  display: block;
  font-weight: 500;
  margin-bottom: 2px;
}

.participant-info {
  font-size: 12px;
  color: #909399;
}

.selected-participants {
  padding: 12px;
  min-height: 60px;
  background: #fafafa;
}

.selected-participant {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: #409eff;
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.btn-remove-participant {
  background: transparent;
  border: none;
  color: white;
  cursor: pointer;
  padding: 2px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.3s ease;
}

.btn-remove-participant:hover {
  background: rgba(255, 255, 255, 0.2);
}

.empty-participants {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .list-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-filter {
    max-width: none;
  }
  
  .modal-content {
    max-width: 95%;
  }
}

@media (max-width: 768px) {
  .module-card {
    padding: 20px;
    margin: 16px;
  }
  
  .module-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-actions {
    align-self: stretch;
    justify-content: flex-end;
  }
  
  .meeting-table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
  }
  
  .calendar-days {
    grid-template-columns: repeat(7, minmax(60px, 1fr));
  }
  
  .calendar-day {
    min-height: 80px;
    padding: 4px;
  }
  
  .day-meetings {
    max-height: 60px;
  }
  
  .modal-header,
  .modal-body,
  .modal-footer {
    padding: 16px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .detail-row {
    flex-direction: column;
    gap: 4px;
  }
  
  .detail-row label {
    width: auto;
  }
}

@media (max-width: 480px) {
  .calendar-days {
    grid-template-columns: repeat(7, 1fr);
  }
  
  .calendar-day {
    min-height: 60px;
    padding: 2px;
  }
  
  .day-number {
    font-size: 12px;
  }
  
  .meeting-item {
    font-size: 10px;
    padding: 2px 4px;
  }
  
  .btn-primary,
  .btn-secondary {
    padding: 8px 16px;
    font-size: 14px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-content {
  animation: fadeIn 0.3s ease-out;
}

/* 滚动条样式 */
.modal-content::-webkit-scrollbar,
.day-meetings::-webkit-scrollbar,
.available-participants::-webkit-scrollbar {
  width: 6px;
}

.modal-content::-webkit-scrollbar-track,
.day-meetings::-webkit-scrollbar-track,
.available-participants::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.modal-content::-webkit-scrollbar-thumb,
.day-meetings::-webkit-scrollbar-thumb,
.available-participants::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.modal-content::-webkit-scrollbar-thumb:hover,
.day-meetings::-webkit-scrollbar-thumb:hover,
.available-participants::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
</style>